import React, { Component } from 'react';
import {BrowserRouter,Switch,Route,Redirect} from "react-router-dom";
import Routes from './routerConfig';
class router extends Component {
  //定义函数完成普通路由构建
  createBasicRoute(router,index){
    return <Route key={index} exact path={router.path} component={router.component}></Route>
  }
  //定义函数完成子级路由构建
  createChildrenRoute(router){
    //创建一个子级路由实例
    return (
      <router.component>
        <Switch>
          {
            router.children.map((router1,index1)=>{
              let router_temp = {...router1,path:router.path+"/"+router1.path};
              return this.createBasicRoute(router_temp,index1);
            })
          }
          {
            <Redirect from={router.path} to={router.path+"/"+router.children[0].path} />
          }
        </Switch>
      </router.component>
    )
  }
  render() {
    return (
      <BrowserRouter>
        <Switch>
          {Routes.map((router,index)=>{
            if(router.children){
              //代表该路由需要构建一个子级路由
              return <Route key={index} path={router.path} children={()=>this.createChildrenRoute(router)} />
            }else{
              //代表该路由只需构建一个根路由
              return this.createBasicRoute(router,index)
            }
          })}
        </Switch>
      </BrowserRouter>
    );
  }
}

export default router;